#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@Introduce :
@File      : works.py
@Time      : 2022/8/5 20:00
@Author    : toby
"""

from flask import Blueprint,request,jsonify
import logging
from celery.result import AsyncResult
from dbs import db
from models import ApiResult
from celery_task.tasks import apitest,sendMail
from utils.operadirectory import as_dict,getFlist

# 注册的蓝图 ,url_prefix 在所有的路径前面增加/user
bp = Blueprint('works',__name__,url_prefix='/works')
logger = logging.getLogger(__name__)

TESTSCRIPT ="/root/flask-celery-hjw/flask-celery/pytest_pkg/testcase-data/"


# 接口测试  任务
@bp.route('/v1/task/apiTest',methods=['GET'])
def apiTest():
    print(' route  API接口 test')
    apitask = apitest.apply_async()
    try:
        api_response = ApiResult(projectname='APITEST',taskid =apitask.id,result=apitask.status)
        # session记录对象任务
        db.session.add(api_response)
        # 提交任务到数据库中
        db.session.commit()

        return jsonify({'msg':'apiTest Success!',"task_id":apitask.id,"code":200})
    except Exception as e:
        db.session.rollback()  # 事务回滚
        return jsonify({'action':e,"task_id":apitask.id,"code":-1})


# 发送邮件测试  任务
@bp.route('/v1/task/send_mail',methods=['GET'])
def send_mail():
    """Background task that runs a long function with progress reports."""
    email_task = sendMail.apply_async()
    # cesu_task = cesutask.apply_async()
    print("send_mail")
    print("cesu_task")
    return jsonify({'action':"sendEmail","task_id":email_task.id,"code":200})

# 查询单个任务状态
@bp.route('/v1/task/status/<taskname>/<task_id>',methods=['GET'])
def taskstatus(taskname,task_id):
    print("task_id:{}".format(task_id))
    print("taskname:{}".format(taskname))
    if taskname.lower()=='apitest':
        task= apitest.AsyncResult(task_id)
        print("task.id:{}".format(task.id))
        print("task.status:{}".format(task.status))
        resonse = {
            'id':task.id,
            'status':task.status

        }
        return jsonify(resonse)

# 更新单个任务状态
@bp.route('/v1/task/upstatus/<task_id>/<result>',methods=['GET'])
def taskstatusupdate(task_id,result):

    print("get task_id:{}".format(task_id))
    print(" get result:{}".format(result))
    try:
        query = ApiResult.query.filter_by(taskid=task_id).update({'result':result})
        # print(query)
        # query.result = result
        # 提交任务到数据库中
        db.session.commit()
        return jsonify({'code': 200, "msg": "update success !"})
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': -1, "msg": "update failed ! {}".format(e)})





        # 查询执行的结果  查询
@bp.route('/v1/task/query',methods=['GET'])
def apitaskquery():
    if request.method =="GET":
        # 查询数据库中的所有任务 最后20个数据
        querydata = ApiResult.query.order_by(ApiResult.id.desc()).limit(20)
        # 分页查询  ,查询第2页的数据,每页3个  基于Sqlalchemy 实现的分页器 QueryPaginate
        # pn = ApiResult.query.paginate(page=1, per_page=10, error_out=True)
        # # pn.items 获取到该页的数据 ,pn.page获取当前的页码 ,pn.page获取总页数
        # collections = pn.items
        # print(collections)
        # # 获取当前页码
        # current_page = pn.page
        # # 获取总页数
        # total_page = pn.pages
        data_list = []
        for item in querydata:
            data_list.append(as_dict(item))
        return jsonify({"code": 200, "res": data_list})


@bp.route("/v1/task/getscriptlist.json",methods=['GET'])
def getfilelist():
    # 文件列表
    res_list = getFlist(TESTSCRIPT)
    # keys = [key for key in range(len(res_list))]
    m =map(lambda key,value: {"value":key,"label":value},res_list,res_list)
    print(res_list )
    dc = {
        "code":200,
        "filelist":list(m),
    }
    return jsonify(dc)
    # map() 会根据提供的函数对指定序列做映射。
    # 第一个参数 function 以参数序列中的每一个元素调用 function 函数，返回包含每次 function 函数返回值的新列表
    # map(func(),iterable)

